import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter_comm_base_framework/core/utils/ColorsUtil.dart';
import 'package:flutter_comm_base_framework/core/utils/string_utils.dart';

import 'custom_text.dart';

class CustomHHTimerView extends StatefulWidget{
  int _millSecs;
  Color _color;
  double _txSize;

  CustomHHTimerViewState hhTimerViewState;

  ///　millSecs 倒计时时长的毫秒值
  /// 转换为时分秒倒计时
  CustomHHTimerView(int millSecs,{Color color = ColorsUtil.blue_dark1,double txSize = 12}){
    this._millSecs = millSecs;
    this._color = color;
    this._txSize = txSize;
  }

  @override
  State<StatefulWidget> createState() {
    return CustomHHTimerViewState();
  }

}
class CustomHHTimerViewState extends State<CustomHHTimerView>{
  String _showText;

  /// 倒计时的计时器。
  Timer _timer;
  /// 当前倒计时的秒数。
  int _seconds;

  @override
  void initState() {
    super.initState();

    _seconds = widget._millSecs~/1000;
    _showText = StringUtils.secToTime(_seconds);

    Future.delayed(Duration(milliseconds: 100), () {
      _startTimer();
    });
  }

  @override
  Widget build(BuildContext context) {
    _showText = StringUtils.secToTime(_seconds);
    return CustomText(_showText,textColor: widget._color,textSize: widget._txSize);
  }

  /// 启动倒计时的计时器。
  void _startTimer() {
    // 计时器（`Timer`）组件的定期（`periodic`）构造函数，创建一个新的重复计时器。
    _timer = Timer.periodic(
        Duration(seconds: 1), (timer) {
          if (_seconds <= 0) {
            _cancelTimer();
            return;
          }
          setState(() {
            _seconds--;
            _showText = StringUtils.secToTime(_seconds);
          });
        });
  }

  /// 取消倒计时的计时器。
  void _cancelTimer() {
    // 计时器（`Timer`）组件的取消（`cancel`）方法，取消计时器。
    _timer?.cancel();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _cancelTimer();
    super.dispose();
  }
}